import React from "react";
import {Table, Popconfirm, Form, InputNumber, Input, Button, message} from 'antd';
import { Resizable } from 'react-resizable';
import PropTypes from 'prop-types';
import EditableContext from "@/components/table/EditableContext";
import EditableCell from "@/components/table/EditableCell";


const ResizeableTitle = props => {
    const { onResize, width, ...restProps } = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps} />
        </Resizable>
    );
};

const data = [];
for (let i = 0; i < 19; i++) {
    data.push({
        key: i.toString(),
        name: `Edrward ${i}`,
        age: 22,
        address: `London Park no. ${i}`,
    });
}


class EditTable extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            data:data,
            size:10,
            editingKey: "", // 记录当前编辑行
            selectedRowKeys: [], // 批量操作选中行
            locale: {
                filterConfirm: '确定',
                filterReset: '重置',
                emptyText: '暂无数据'
            },
            columns: [
                {
                    title: '姓名',
                    dataIndex: 'name',
                    width: 150,
                    align: "center",
                    editable: true // 自定义属性
                },
                {
                    title: '年龄',
                    dataIndex: 'age',
                    width: 100,
                    align: "center",
                    editable: true
                },
                {
                    title: '地址',
                    dataIndex: 'address',
                    width: 300,
                    align: "center",
                    editable: true
                },
                {
                    title: '时间',
                    dataIndex: 'date',
                    width: 150,
                    align: "center",
                    editable: true
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    width: 200,
                    align: "center",
                    render: (text, record, index) => {
                        const {editingKey} = this.state;
                        const editable = this.isEditing(record);
                        return editable ? (
                            <span>
                                <EditableContext.Consumer>
                                    {form => (
                                        <a onClick={() => this.save(form, record.key)} style={{ marginRight: 8 }}>
                                            修改
                                        </a>
                                    )}
                                </EditableContext.Consumer>
                                <Popconfirm title="Sure to cancel?" onConfirm={ () => this.cancel()}>
                                    <a>取消</a>
                                </Popconfirm>
                            </span>
                        ) : (
                            <span>
                                <a disabled={editingKey !== ''} onClick={ () => {this.edit(record.key)} }> 编辑 </a>
                                <a disabled={editingKey !== ''} onClick={ () => {this.remove([record.key])} }> 删除 </a>
                            </span>

                        )
                    }
                },
            ]
        };

    }

    // 判断编辑行
    isEditing = record => record.key === this.state.editingKey;

    // 取消修改
    cancel() {
        this.setState({ editingKey: '' });
    }

    // 保存修改
    save(form, key) {
        form.validateFields((error, row) => {
            if (error) {
                return;
            }
            // 处理时间格式
            const newRow = {...row, "date": row['date'].format("YYYY-MM-DD")};
            const newData = [...this.state.data];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...newRow
                });
                this.setState({ data: newData, editingKey: '' });
            } else {
                newData.push(row);
                this.setState({ data: newData, editingKey: '' });
            }
        });
    }

    // 编辑
    edit(key) {
        this.setState({ editingKey: key });
    }

    // 单个删除/批量删除
    remove(keys) {
        const newData = [...this.state.data];
        keys.map(key => {
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                newData.splice(index, 1);
            }
        });
        this.setState({data: newData, selectedRowKeys: []});
    }

    // 添加一行
    addRow() {
        const newData = this.state.data;
        const { editingKey } = this.state;
        if (editingKey !== '') {
            message.error('请先保存正在编辑的行');
            return;
        }
        const key = new Date().getTime();
        console.log(key);
        // newData.push({
        //     key: key,
        //     name: '',
        //     age: '',
        //     address: '',
        //     date: ""
        // });
        // this.setState({data: newData});
    }

    //选择
    onSelectChange = selectedRowKeys => {
        console.log("哈哈");
        this.setState({selectedRowKeys})
    }

    //通过拖拽可伸缩列
    handleResize = index => (e, { size }) => {
        this.setState(({ columns }) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return { columns: nextColumns };
        });
    };

    // 页数
    sizeChange = (current,size) => {
        this.setState({
            size: size
        })
    }

    // 搜索
    handleSearch  = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
        });
    }

    // 重置
    handleReset = () => {
        this.props.form.resetFields();
    }

    components = {
        header: {
            cell: ResizeableTitle,
        },
        body: {
            cell: EditableCell,
        },
    };

    render() {
        const columns = this.state.columns.map((col, index) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onHeaderCell: column => ({ // 设置头部单元格属性
                    width: column.width,
                    onResize: this.handleResize(index),
                }),
                onCell: record => ({ // 设置单元格属性
                    record,
                    inputType: col.dataIndex === 'age' ? 'number' : (col.dataIndex === 'date' ? 'datatime' : 'text'),
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                }),
            }

        });
        const { selectedRowKeys } = this.state;
        const hasSelected = selectedRowKeys.length > 0;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        }
        const { getFieldDecorator } = this.props.form;
        return (
           <EditableContext.Provider value={this.props.form}>
               <Form className="table_search" onSubmit={this.handleSearch}>
                   <Form.Item label='姓名'>
                       {getFieldDecorator('name', {
                           rules: [{message: 'input someting'}]
                       })(<Input placeholder='请输入搜索内容。。。'/>)}
                   </Form.Item>
                   <Form.Item label='年龄'>
                       {getFieldDecorator('age', {
                           rules: [{message: 'input someting'}]
                       })(<Input placeholder='请输入搜索内容。。。'/>)}
                   </Form.Item>
                   <Form.Item label='地址'>
                       {getFieldDecorator('address', {
                           rules: [{message: 'input someting'}]
                       })(<Input placeholder='请输入搜索内容。。。'/>)}
                   </Form.Item>
                   <Form.Item>
                       <Button type="primary" icon="search" htmlType="submit">搜索</Button>
                   </Form.Item>
                   <Form.Item>
                       <Button type="primary" icon="redo" onClick={this.handleReset}>重置</Button>
                   </Form.Item>
               </Form>
               <div className="table_top">
                   <Button type="primary" disabled={hasSelected} onClick={ () => this.addRow()} className="add">新增</Button>
                   <Button type="primary" disabled={!hasSelected} onClick={() => this.remove(selectedRowKeys)} className="delete">批量删除</Button>
                   <span>已选择 {selectedRowKeys.length} 项</span>
               </div>
               <Table
                    bordered
                    components={this.components}
                    columns={columns}
                    dataSource={this.state.data}
                    rowSelection={rowSelection}
                    pagination={{pageSize:this.state.size, showSizeChanger:true,pageSizeOptions:['10',"20","30"],onShowSizeChange:this.sizeChange}}
               />
            </EditableContext.Provider>
        )
    }

}

export default Form.create()(EditTable);
// 指定form为对象类型
EditTable.propTypes = {
    form: PropTypes.object,
};
